import React, {ReactNode, useState} from "react";
import * as auth from '../auth-provider'
import {LoginFieldType} from "../types/user";

const AuthContext = React.createContext<{
    token: string | null,
    login: (form: LoginFieldType) => Promise<void>,
    register: (form: LoginFieldType) => Promise<void>,
    logout: () => Promise<void>,
} | undefined>(undefined);

AuthContext.displayName = 'AuthContext';


export const AuthProvider = ({children}: { children: ReactNode }) => {
    const [token, setToken] = useState<string | null>(auth.getToken())

    const login = async (loginForm: LoginFieldType) => auth.handleLogin(loginForm).then(setToken)

    const register = (loginForm: LoginFieldType) => auth.handleRegister(loginForm)

    const logout = () => auth.logout().then(() => setToken(''))

    return <AuthContext.Provider children={children} value={{token, login, register, logout}}/>
}

export const useAuth = () => {
    const context = React.useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth 必须在 AuthProvider 中使用')
    }
    return context
}